package com.eningqu.aipen.demo.common;

import android.text.TextUtils;

import java.io.File;
import java.net.FileNameMap;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URLConnection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * @Author: Qiu.Li
 * @Create Date: 2020/10/20 14:11
 * @Description: 通信工具类
 * @Email: liqiupost@163.com
 */
public class HttpUtils {
    private static OkHttpClient client = null;

    private HttpUtils() {
    }

    public static OkHttpClient getInstance() {
        if (client == null) {
            synchronized (HttpUtils.class) {
                if (client == null) {
                    client = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS)
                            .readTimeout(20, TimeUnit.SECONDS)
                            .writeTimeout(10, TimeUnit.SECONDS)
                            .build();
                }
            }
        }
        return client;
    }

    /**
     * Get请求
     *
     * @param url
     * @param callback
     */
    public static void doGet(String url, String token, Callback callback) {
        Request request = new Request.Builder()
                .url(url)
                .addHeader("auth_token", token)
                .build();
        Call call = getInstance().newCall(request);
        call.enqueue(callback);
    }

    public static void doGet(String url, Callback callback) {
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = getInstance().newCall(request);
        call.enqueue(callback);
    }

    /**
     * Post请求发送键值对数据
     *
     * @param url
     * @param mapParams
     * @param callback
     */
    public static void doPost(String url, Map<String, String> mapParams, Callback callback) {
        FormBody.Builder builder = new FormBody.Builder();
        for (String key : mapParams.keySet()) {
            builder.add(key, mapParams.get(key));
        }
        Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .build();
        Call call = getInstance().newCall(request);
        call.enqueue(callback);
    }

    /**
     * Post请求发送JSON数据
     *
     * @param url
     * @param jsonParams
     * @param callback
     */
    public static void doPost(String url, String jsonParams, Callback callback) {
        Map<String, String> map = new HashMap<>();
        map.put("dataJson", jsonParams);
        //处理参数
        FormBody.Builder builder = new FormBody.Builder();
        addParams(builder, map);
        FormBody formBody = builder.build();

        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();
        Call call = getInstance().newCall(request);
        call.enqueue(callback);
    }

    private static void addParams(FormBody.Builder builder, Map<String, String> params) {
        if (params != null) {
            for (String key : params.keySet()) {
                builder.add(key, params.get(key));
            }
        }
    }

    /**
     * 上传文件
     *
     * @param url
     * @param pathName
     * @param fileName
     * @param callback
     */
    public static void doFile(String url, String pathName, String fileName, String token, String bookNo, Callback callback) {
        //判断文件类型
        //        bookNo = bookNo.replace(" ","").replace("-", "").replace(":", "");
        MediaType MEDIA_TYPE = MediaType.parse(judgeType(pathName));
        Map<String, String> map = new HashMap<>();
        //        map.put("hashValue", getFileMD5(new File(pathName)));
        map.put("bookName", fileName);
        map.put("bookNo", bookNo);
        File file = new File(pathName);

        MultipartBody.Builder multipartBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
        multipartBody.addFormDataPart("zipFile", fileName, RequestBody.create(MEDIA_TYPE, file));
        if (map != null) {
            // map 里面是请求中所需要的 key 和 value
            for (String key : map.keySet()) {
                multipartBody.addFormDataPart(key, map.get(key));
            }
        }
        //发出请求参数
        Request request = new Request.Builder()
                .header("auth_token", token)
                .url(url)
                .post(multipartBody.build())
                .build();
        Call call = getInstance().newCall(request);
        call.enqueue(callback);
    }

    /**
     * 根据文件路径判断MediaType
     *
     * @param path
     * @return
     */
    private static String judgeType(String path) {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String contentTypeFor = fileNameMap.getContentTypeFor(path);
        if (contentTypeFor == null) {
            contentTypeFor = "application/octet-stream";
        }
        return contentTypeFor;
    }

    /**
     * 下载文件
     *
     * @param url
     */
    public static void downFile(String url, Callback callback) {
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = getInstance().newCall(request);
        call.enqueue(callback);

          /*@Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                try {
                    is = response.body().byteStream();
                    File file = new File(fileDir, fileName);
                    fos = new FileOutputStream(file);
                    //---增加的代码---
                    //计算进度
                    long totalSize = response.body().contentLength();
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        sum += len;
                        //progress就是进度值
                        int progress = (int) (sum * 1.0f/totalSize * 100);
                        //---增加的代码---
                        fos.write(buf, 0, len);
                    }
                    fos.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (is != null) is.close();
                    if (fos != null) fos.close();
                }
            }*/

    }

    /**
     * Android 7.0之后获取Mac地址
     * 遍历循环所有的网络接口，找到接口是 wlan0
     * 必须的权限 <uses-permission android:name="android.permission.INTERNET"></uses-permission>
     *
     * @return
     */
    public static byte[] getMacFromHardware() {
        try {
            Enumeration<NetworkInterface> all = NetworkInterface.getNetworkInterfaces();

            if (all != null) {
                while (all.hasMoreElements()) {

                    NetworkInterface nif = all.nextElement();
                    if (!nif.getName().equals("wlan0"))
                        continue;
                    byte macBytes[] = nif.getHardwareAddress();
                    if (macBytes == null)
                        return null;
//                    StringBuilder res1 = new StringBuilder();
//                    for (Byte b : macBytes) {
//                        res1.append(String.format("%02X:", b));
//                    }
//                    if (!TextUtils.isEmpty(res1)) {
//                        res1.deleteCharAt(res1.length - 1)
//                    }
                    return macBytes;
                }
            }

        } catch (SocketException e) {
            e.printStackTrace();
        }

        return null;
    }
}
